package io.renren.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.stereotype.Controller;

import io.renren.entity.DictEmployeeEntity;
import io.renren.entity.xtd.DataPayrollEntityXtd;
import io.renren.entity.xtd.DictEmployeeEntityXtd;
import io.renren.service.DataEmpPerformanceService;
import io.renren.service.DictDepartmentService;
import io.renren.service.DictEmployeeService;
import io.renren.service.SysWorkLogService;
import io.renren.service.xtd.DataContractpayServiceXtd;
import io.renren.service.xtd.DataPayrollServiceXtd;
import io.renren.service.xtd.DictEmployeeServiceXtd;
import io.renren.service.xtd.HisEmployeeServiceXtd;
import io.renren.utils.AssignUtils;
import io.renren.utils.Common;
import io.renren.utils.ExcelUtils;
import io.renren.utils.PageUtils;
import io.renren.utils.R;
import io.renren.utils.ShiroUtils;


/**
 * 员工表
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-05-21 10:23:03
 */
@Controller
@RequestMapping("dictemployee")
public class DictEmployeeController {
	@Autowired
	private SysWorkLogService sysWorkLogService;
	@Autowired
	private DataContractpayServiceXtd dataContractpayServiceXtd;
	@Autowired
	private HisEmployeeServiceXtd hisEmployeeServiceXtd;
	@Autowired
	private DictDepartmentService dictDepartmentService;
	@Autowired
	private DictEmployeeService dictEmployeeService;
	@Autowired
	private DictEmployeeServiceXtd dictEmployeeServiceXtd;
	@Autowired
	private DataPayrollServiceXtd dataPayrollServiceXtd;
	@Autowired
	private DataEmpPerformanceService dataEmpPerformanceService;
	@RequestMapping("/dictemployee.html")
	public String list(){
		return "dictemployee/dictemployee.html";
	}
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("dictemployee:list")
	public R list(Integer page, Integer limit,String value){
		Map<String, Object> map = new HashMap<>();
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);
		map.put("value", value);
		//查询列表数据
		List<DictEmployeeEntityXtd> dictEmployeeList = dictEmployeeServiceXtd.queryListXtd(map);
		int total = dictEmployeeService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(dictEmployeeList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 */
	@ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("dictemployee:info")
	public R info(@PathVariable("id") String id){
		DictEmployeeEntity dictEmployee = dictEmployeeService.queryObject(id);
		
		return R.ok().put("dictEmployee", dictEmployee);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	@RequiresPermissions("dictemployee:save")
	public R save(@RequestBody DictEmployeeEntity dictEmployee){
		if(!StringUtils.isBlank(dictEmployee.getWorkno())){
			Map<String, Object> mapa = new HashMap<>();
			mapa.put("workNo", dictEmployee.getWorkno());
			int total = dictEmployeeServiceXtd.queryTotalByMore(mapa);
			if(total!=0){
				return R.error("此员工编号已被使用");
			}
			}
		if(dictEmployee.getUserid()!=null){
		Map<String, Object> map = new HashMap<>();
		map.put("userId", dictEmployee.getUserid());
		int total = dictEmployeeServiceXtd.queryTotalByMore(map);
		if(total!=0){
			return R.error("此关联账号已被使用");
		}
		}
		
		dictEmployeeService.save(dictEmployee);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("dictemployee:update")
	public R update(@RequestBody DictEmployeeEntity dictEmployee){
		if(!StringUtils.isBlank(dictEmployee.getWorkno())){
			Map<String, Object> mapa = new HashMap<>();
			mapa.put("workNo", dictEmployee.getWorkno());
			mapa.put("isnotId", dictEmployee.getId());
			int total = dictEmployeeServiceXtd.queryTotalByMore(mapa);
			if(total!=0){
				return R.error("此员工编号已被使用");
			}
			}
		if(dictEmployee.getUserid()!=null){
			Map<String, Object> map = new HashMap<>();
			map.put("userId", dictEmployee.getUserid());
			map.put("isnotId", dictEmployee.getId());
			int total = dictEmployeeServiceXtd.queryTotalByMore(map);
			if(total!=0){
				return R.error("此关联账号已被使用");
			}
			}
			
		dictEmployeeService.update(dictEmployee);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("dictemployee:delete")
	public R delete(@RequestBody String[] ids){
		dictEmployeeService.deleteBatch(ids);
		
		return R.ok();
	}
	/**
	 * 整体信息
	 */
	@ResponseBody
	@RequestMapping("/infoxtd/{id}")
	@RequiresPermissions("dictemployee:info")
	public R infoxtd(@PathVariable("id") String id){
		DictEmployeeEntityXtd queryObjectXtd = dictEmployeeServiceXtd.queryObjectXtd(id);
		
		return R.ok().put("dictEmployeeXtd", queryObjectXtd);
	}
	
	/**
	 * 导入excel
	 * @throws Exception 
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile multfile,String time) throws Exception{ 

		/*try {*/
			if(time==null || time.length()==0 || time.indexOf("-")<0){
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入失败",
	        			"未选择数据时间", "");
				return R.error("请选择数据时间");
			}
			R resultR = ExcelUtils.textEmpExcel(multfile.getInputStream(),0);
			if (Integer.parseInt(resultR.get("code").toString())!=0) {
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入失败",
	        			resultR.get("msg").toString(), time);
				return resultR;
				
			}
			Map<String, Object> mape=new HashMap<>();
			int total = dictDepartmentService.queryTotal(mape);
			if(total==0){
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入失败",
	        			"未导入组织架构数据", time);
				return R.error("请先导入组织架构数据");
			}
			Integer showType=0;
			Map<String, Object> map=new HashMap<>();
			map.put("year", Integer.parseInt(time.split("-")[0]));
			map.put("month", Integer.parseInt(time.split("-")[1]));
			
			total = hisEmployeeServiceXtd.queryTotalXtd(map);
			if (total>0) {
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入失败",
	        			"已有历史数据，不可再导入", time);
				return R.error("已有历史数据，不可再导入");
			} else {
				if(Integer.valueOf(map.get("month").toString())==1){
					map.remove("year");
					map.put("year", Integer.parseInt(time.split("-")[0])-1);
					map.remove("month");
					map.put("month", 12);
				}else{
					map.remove("month");
					map.put("month", Integer.parseInt(time.split("-")[1])-1);
				}
				total = hisEmployeeServiceXtd.queryTotalXtd(map);
				Map<String, Object> hismap=new HashMap<>();
				int histotal = hisEmployeeServiceXtd.queryTotalXtd(hismap);
				if(total==0 && histotal!=0){
					Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
		        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入失败",
		        			"请先将上个月员工数据转存历史，再导入", time);
					return R.error("请先将上个月员工数据转存历史，再导入");
				}
				Map<String, Object> mapb=new HashMap<>();
				mapb.put("year", time.split("-")[0]);
				mapb.put("month", time.split("-")[1]);
				total = dataContractpayServiceXtd.queryTotalXtd(mapb);
				if(total==0){
					showType=0;
				}else{
					showType=1;
				}
			}
			Map<String, Object> mapc = new HashMap<>();
			List<DictEmployeeEntity> dictEmployeeList = dictEmployeeService.queryList(mapc);
			List<List<Object>> list = ExcelUtils.readExcel2(multfile.getInputStream(),0);
			List<Map<String,Object>> emps = AssignUtils.assignToEmpNewUuid(list,dataEmpPerformanceService);
			if (dictEmployeeList==null || dictEmployeeList.size()==0) {
				
				dictEmployeeServiceXtd.impExcelInList(emps);
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入成功",
	        			"", time);
				return R.ok();	
			}else{
				
				if (emps==null || emps.size()==0) {
					dictEmployeeServiceXtd.impExcelInList(emps);
					Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
		        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入成功",
		        			"", time);
					return R.ok();	
				} else {
                    for(int n=0;n<emps.size();n++){
                    	Map<String, Object> mapd = emps.get(n);
                    	for(int m=0;m<dictEmployeeList.size();m++){
                    		if(dictEmployeeList.get(m).getWorkno().equals(mapd.get("workno"))){
                    			emps.get(n).remove("id");
                    			emps.get(n).put("id", dictEmployeeList.get(m).getId());
                    			break;
                    		}
                    	}
                    }
                    dictEmployeeServiceXtd.deleteAll();
                    dictEmployeeServiceXtd.impExcelInList(emps);
                    Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
    	        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入成功",
    	        			"", time);
					return R.ok();	
				}
			}

			/*} catch (Exception e) {
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
        			ShiroUtils.getUserEntity().getUsername(), "员工数据导入失败",
        			"导入失败", time);
			return R.error("导入失败");
		}*/

	}

	/**
	 * 检查覆盖
	 */
	@ResponseBody
	@RequestMapping("/hashisdata")
	public R hasHisData(HttpServletRequest request){ 
		String date = request.getParameter("time");
		Map<String, String> time = new HashMap<String, String>();
		time.put("year", date.substring(0,4));
		time.put("month", date.substring(5,7));
		if(dictEmployeeServiceXtd.hasHisData(time)==0){
			return  R.ok();
		}
		return  R.error();
	}
	
	/**
	 * 存入历史
	 */
	@ResponseBody
	@RequestMapping("/history")
	public R history(HttpServletRequest request){ 
		String date = request.getParameter("time");
		Map<String, String> time = new HashMap<String, String>();
		time.put("year", date.substring(0,4));
		time.put("month", date.substring(5,7));
    	if(dictEmployeeServiceXtd.toHistory(time)!=0){
/*			dictEmployeeServiceXtd.emptyEmployee();*/
		}
		
		return  R.ok();
	}
	/**
	 * 
	 * 返回最新工资列表
	 */
	@RequestMapping(value="/payrollone/{userId}",method=RequestMethod.GET)
	@ResponseBody
	public R getRoleName(@PathVariable("userId") String userId){
		DictEmployeeEntityXtd empByUserid = dictEmployeeServiceXtd.getEmpByUserid(userId);
		if(empByUserid==null) {
			return R.error("没有关联用户");
		}
		List<DataPayrollEntityXtd> queryByWorkno = dataPayrollServiceXtd.queryByWorkno(empByUserid.getWorkno());
		List<DataPayrollEntityXtd> payrollone=new ArrayList<>();
		payrollone.add(queryByWorkno.get(queryByWorkno.size()-1));
		return R.ok().put("payrollone", payrollone);
		
	}
	
}
